//
//  ComposeViewController.swift
//  Weibo
//
//  Created by 周先生 on 15/11/20.
//  Copyright © 2015年 周先生. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {

    //监听方法
    @objc private func selectorPicture() {
        selectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(224 + 80 + 40)
        }
    
    }
    //关闭
    @objc private func close() {
      dismissViewControllerAnimated(true, completion: nil)
    }
    //发布
    @objc private func send() {
//        let urlString = "2/statuses/update.json"
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        guard let token = UserAccountViewModel().token else{
            SVProgressHUD.showErrorWithStatus("您还未登陆")
        return
        }
        
        if selectorVC.imageList.count >= 1 {
            let imageData = UIImagePNGRepresentation(selectorVC.imageList[0])
            let parameter = ["access_token": token, "status": textView.text]
            NetWorkTools.sharedTools.uploadImage(urlString, parameter: parameter, imageData: imageData!, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("您还未登陆啊啊啊啊")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发布成功")
            })
        }
        
//        let parameter = ["access_token": token, "status": textView.text]
//        NetWorkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parameter: parameter) { (result, error) -> () in
//            if error != nil {
//                SVProgressHUD.showErrorWithStatus(AppErrorTip)
//                return
//            }
//                SVProgressHUD.showSuccessWithStatus("发布成功")
//            self.dismissViewControllerAnimated(true, completion: nil)
//            print(result)
        
    
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }
    
    //设置UI
    private func setupUI() {
        //设置导航条
        setNavBar()
        //设置输入文本框
        setupTextView()
        //工具条
        setupToolBar()
        
        //添加图片选择控制器视图
        setSelectorView()
        //注册通知
        registerNotification()
    }
    //根据键盘动态设置toolbar
    
    private func registerNotification() {
    //添加通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    
    }
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    //通知响应方法
    @objc private func keyboardWillChange(n: NSNotification) {
        print(n)
        //获取动画时间
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //修改toolbar约束
        //获取键盘高度
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in  //更新约束
            make.bottom.equalTo(offset)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            //强制刷新
            self.view.layoutIfNeeded()
        }
    
    }
    //懒加载控件
    private lazy var textView: UITextView = {
        let tv = UITextView()
        //设置代理
        tv.delegate = self
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.darkGrayColor()
        //设置键盘消失
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置弹簧效果开启
        tv.alwaysBounceVertical = true
        return tv
    }()
    
    private func setSelectorView() {
        //添加子控制器视图
        addChildViewController(selectorVC)
        //添加视图
        view.addSubview(selectorVC.view)
        //调整视图层次结构
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    
    }
    //懒加载控件
    private lazy var placeHolderLabel: UILabel = UILabel(title: "快来分享属于你的..", size: 18, color: UIColor.lightGrayColor())
    //工具条
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //照片选择器
    private lazy var selectorVC: PictureSelectorViewController = PictureSelectorViewController()
    
    
}

extension ComposeViewController: UITextViewDelegate {
    //
    func textViewDidChangeSelection(textView: UITextView) {
        //设置占位文本隐藏
        placeHolderLabel.hidden = textView.hasText()
        //设置发布按钮的交互
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    
    }

    //设置底部工具栏
    private func setupToolBar() {
        view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(40)
            
        }
        //设置toolBar按钮 及点击事件
        var items = [UIBarButtonItem]()
        //添加UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectorPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_add_background"]]
        //设置textView
        for dict in itemSettings{
            let btn = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(btn)
            //实例化弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //删除最后一个弹簧
        items.removeLast()
        toolBar.items = items
    }

    private func setupTextView() {
        view.addSubview(textView)
//        textView.backgroundColor = UIColor.randomColor()
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.height / 3)
        }
        
        //添加占位文本
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    //设置导航条
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        //        titleView.backgroundColor = UIColor.lightGrayColor()
        navigationItem.titleView = titleView
        //添加导航栏 发布信息的UILabel
        let titleLabel = UILabel(title: "发微博", size: 17, color: UIColor.lightGrayColor())
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.lightGrayColor())
        //添加子视图
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
    



}